package com.example.demo.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.time.ZonedDateTime;

//处理异常的逻辑：
//输入要处理的异常（ApiRequestException)--> 生成ApiException类 -->
//结合ApiException和Http状态生成响应实体实例(ResponseEntity) --> 返回客户端

//@ControllerAdvice注解：让ApiExceptionHandler中的java类
// 可存放处理异常的方法（有ExceptionHandler注解的方法)

@ControllerAdvice
public class ApiExceptionHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);

//  @ExceptionHandler注解：加在类方法上面
//  @ExceptionHandler的参数：英文输入法,ctrl+空格,获得可输入选项的建议
//    此参数表面该方法处理的异常为ApiRequestException

    @ExceptionHandler(value = ApiRequestException.class)
    public ResponseEntity<Object> handleApiRequestException(
            ApiRequestException e
    )
    {

        ApiException apiException = new ApiException(
                e.getMessage(),
                e, HttpStatus.BAD_REQUEST,
                ZonedDateTime.now()
        );
        return new ResponseEntity<>(apiException,HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = NotFoundException.class)
//    @ExceptionHandler注解：(参数 = NotFoundException.class)
//    该方法处理的异常为NotFoundException.class
    public ResponseEntity<Object> handleNotFoundException(
            NotFoundException e
    )
    {

        ApiException apiException = new ApiException(
                e.getMessage(),
                e,
                HttpStatus.NOT_FOUND,
                ZonedDateTime.now()
        );
        return new ResponseEntity<>(apiException,HttpStatus.NOT_FOUND);
    }
}
